package com.wephone.Student;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.google.gson.Gson;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.huanxin.Constant;
import com.wephone.Student.huanxin.domain.User;
import com.wephone.Student.ui.BaseActivity;
import com.wephone.Student.ui.LoginActivity;
import com.wephone.Student.ui.MainTabBar;
import com.wephone.Student.ui.RegisterActivity;
import com.wephone.Student.util.ShareReferenceUtil;

public class MainActivity extends BaseActivity{
	private static long backClickTime = -1;
//	private GridView gridview;
//	private GridViewAdapter adapter;
	//baidu location
//	public LocationClient mLocationClient = null;
//	public BDLocationListener myListener = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		init();
	}
	
	@Override
	public void onDestroy() {
//		mLocationClient.stop();
		super.onDestroy();
	}

	private void init(){
//		imageLoader.clearDiscCache();
//		gridview = (GridView)findViewById(R.id.gridview);
//		adapter = new GridViewAdapter();
//		gridview.setAdapter(adapter);
		
		findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(getApplicationContext(),LoginActivity.class));
				finish();
			}
		});
		
		findViewById(R.id.btn_register).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
				finish();
			}
		});
		
//		myListener = new MyLocationListener(getApplicationContext());
//		mLocationClient = new LocationClient(getApplicationContext());
//		mLocationClient.registerLocationListener(myListener);
//		LocationClientOption option = new LocationClientOption();
//		option.setOpenGps(true);
//		option.setAddrType("all");//返回的定位结果包含地址信息
//		option.setCoorType("gcj02");//返回的定位结果是百度经纬度,默认值gcj02,bd09ll
//		option.setScanSpan(1);//设置发起定位请求的间隔时间
//		option.disableCache(true);//禁止启用缓存定位
//		option.setPoiNumber(0);	//最多返回POI个数	
//		option.setPoiDistance(0); //poi查询距离
//		mLocationClient.setLocOption(option);
//		mLocationClient.start();
//		if (mLocationClient != null && mLocationClient.isStarted()){
//			mLocationClient.requestLocation();
//		}
		
		String userInfoJson = ShareReferenceUtil.getUserInfoJson(getApplicationContext());
		if(!TextUtils.isEmpty(userInfoJson)){
			Gson gson = new Gson();
			final UserInfoData infoData = gson.fromJson(userInfoJson, UserInfoData.class);
//			BaseActivity.myInfo = infoData;
			ShareReferenceUtil.saveUserId(getApplicationContext(), infoData.getuId());
//			setAliasAndTags(ShareReferenceUtil.getUserId(getApplicationContext()));
			String infoJson = gson.toJson(infoData);
			ShareReferenceUtil.saveUserInfoJson(getApplicationContext(), infoJson);
			
//			System.out.println("-----1-----"+infoData.getuId());
//			System.out.println("-----2-----"+infoData.getuPwd());
			
//			System.out.println("----BroadcastAction----"+EMChatManager.getInstance().getNewMessageBroadcastAction());
			
			//login huanxin account
			EMChatManager.getInstance().login(infoData.getuId(), infoData.getuPwd(), new EMCallBack() {
				@Override
				public void onError(int arg0, final String errorMsg) {
					runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(MainActivity.this, "登录聊天服务器失败，您将收不到消息", Toast.LENGTH_SHORT).show();
						}
					});
				}

				@Override
				public void onProgress(int arg0, String arg1) {
				}

				@Override
				public void onSuccess() {
					// 登陆成功，保存用户名密码
					BaseApplication.getInstance().setUserName(infoData.getuId());
					BaseApplication.getInstance().setPassword(infoData.getuPwd());
					runOnUiThread(new Runnable() {
						public void run() {
							EMGroupManager.getInstance().loadAllGroups();
							EMChatManager.getInstance().loadAllConversations();
							
						}
					});
					processContactsAndGroups();
//					try {
//						// demo中简单的处理成每次登陆都去获取好友username，开发者自己根据情况而定
//						List<String> usernames = EMChatManager.getInstance().getContactUserNames();
//						System.out.println("-----usernames.size()-----"+usernames.size());
//						Map<String, User> userlist = new HashMap<String, User>();
//						for (String username : usernames) {
//							User user = new User();
//							user.setUsername(username);
//							setUserHearder(username, user);
//							userlist.put(username, user);
//						}
//						// 添加user"新的朋友"
//						User newFriends = new User();
//						newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
//						newFriends.setNick("新的朋友");
//						newFriends.setHeader("");
//						userlist.put(Constant.NEW_FRIENDS_USERNAME,newFriends);
					
					
					
//					List<String> userNameList = EMChatDB.getInstance().findAllParticipantsWithMsg();
//					for(String userName:userNameList){
//						User newFriends = new User();
//						newFriends.setUsername(userName);
//						newFriends.setNick("nick"+userName);
//						newFriends.setHeader("");
//						userlist.put(Constant.NEW_FRIENDS_USERNAME,newFriends);
//					}
					
//						//添加"群聊"
////						User groupUser = new User();
////						groupUser.setUsername(Constant.GROUP_USERNAME);
////						groupUser.setNick("群聊");
////						groupUser.setHeader("");
////						userlist.put(Constant.GROUP_USERNAME, groupUser);
//						
//						//存入内存
//						BaseApplication.getInstance().setContactList(userlist);
//						// 存入db
//						UserDao dao = new UserDao(MainActivity.this);
//						List<User> users = new ArrayList<User>(userlist.values());
//						dao.saveContactList(users);
//
//						// 获取群聊列表,sdk会把群组存入到EMGroupManager和db中
//						EMGroupManager.getInstance().getGroupsFromServer();
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
					
//					EMChat.getInstance().setAppInited();
					
//					runOnUiThread(new Runnable() {
//						public void run() {
//							Toast.makeText(MainActivity.this, "登录聊天服务器成功", Toast.LENGTH_SHORT).show();
//						}
//					});
				}
			});
			//app初始化完毕
//			EMChat.getInstance().setAppInited();
			
			startActivity(new Intent(getApplicationContext(),MainTabBar.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
	                Intent.FLAG_ACTIVITY_CLEAR_TASK |
	                Intent.FLAG_ACTIVITY_NEW_TASK));
			finish();
		}
		
//		if(RegisterActivity.countryList.size()==0){
//			new GetCountryListAsyncTask(getApplicationContext(), handler).execute();
//		}
		initCountryList(getApplicationContext());
	}
	private void processContactsAndGroups(){
        
	     // 获取群聊列表(群聊里只有groupid和groupname等简单信息，不包含members),sdk会把群组存入到内存和db中
	        try {
	            EMGroupManager.getInstance().getGroupsFromServer();
	            Map<String, User> userlist = new HashMap<String, User>();
	     
	            // 添加user"申请与通知"
	            User newFriends = new User();
	            newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
	            String strChat = "系统通知";
	            newFriends.setNick(strChat);

	            userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
	            
	            BaseApplication.getInstance().setContactList(userlist);
	        } catch (EaseMobException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	    }
//	private void setAliasAndTags(String alias){
//		// 检查 tag 的有效性
//		String tag = "Users";
//		// ","隔开的多个 转换成 Set
//		String[] sArray = tag.split(",");
//		Set<String> tagSet = new LinkedHashSet<String>();
//		for (String sTagItme : sArray) {
//			tagSet.add(sTagItme);
//		}
//		JPushInterface.setAliasAndTags(getApplicationContext(), alias, tagSet, this);
//	}

//	private class GridViewAdapter extends BaseAdapter{
//		public int pageIdx = 1;
//		public boolean hasMore = true;
//		
//		@Override
//		public int getCount() {
//			return 30;
//		}
//
//		@Override
//		public Object getItem(int position) {
//			return null;
//		}
//
//		@Override
//		public long getItemId(int position) {
//			return 0;
//		}
//
//		@Override
//		public View getView(int position, View convertView, ViewGroup parent) {
//			if(convertView==null){
//				convertView = getLayoutInflater().inflate(R.layout.include_main_grid_item, null);
//			}
////			ConcertStarByCityData data = starResults.get(position);
////			ImageView itemImage = (ImageView)convertView.findViewById(R.id.item_image);
////			String imgUrl = data.getStarLogo();
////			if(!TextUtils.isEmpty(imgUrl)){
////				if(imgUrl.contains("|")){
////					String[] tmp = imgUrl.split("\\|");
////					imgUrl = tmp[0];
////				}
////				if(!imgUrl.contains("http://")){
////					imageLoader2.displayImage(Constants.API_SERVER_IMAGE+imgUrl, itemImage);
////				}else{
////					imageLoader2.displayImage(imgUrl, itemImage);
////				}
////			}
////			
////			TextView starNameText = (TextView)convertView.findViewById(R.id.star_name_textview);
////			starNameText.setText(data.getGossipStarName());
//			
////			//load more
////			if(position>=starResults.size()-1 && hasMore){
////				RequestParams params2 = new RequestParams();
////				params2.put("cityInfo", cityId);
////				params2.put("appsecret", ShareReferenceUtil.getAppSecret(getApplicationContext()));
////				params2.put("page", ""+pageIdx);
////				params2.put("perPageCount", Constants.PER_PAGE_COUNT);
////				httpClient.post(Constants.API_CONCERT_STAR_BY_CITY, params2, getHandler2(ConcertStarByCityResponse.class));
////			}
//			return convertView;
//		}		
//	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			 long nowTime = System.currentTimeMillis();
				if(backClickTime<=0 || nowTime-backClickTime>2000){
					backClickTime = nowTime;
					Toast.makeText(getApplicationContext(), "再按一次 退出程序", Toast.LENGTH_SHORT).show();
				}else{
					finish();
				}
             return true; 
        }
        return super.onKeyDown(keyCode, event); 
	}
	
//	/**
//	 * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
//	 * 
//	 * @param username
//	 * @param user
//	 */
//	protected void setUserHearder(String username, User user) {
//		String headerName = null;
//		if (!TextUtils.isEmpty(user.getNick())) {
//			headerName = user.getNick();
//		} else {
//			headerName = user.getUsername();
//		}
//		if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
//			user.setHeader("");
//		} else if (Character.isDigit(headerName.charAt(0))) {
//			user.setHeader("#");
//		} else {
//			user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1).toUpperCase());
//			char header = user.getHeader().toLowerCase().charAt(0);
//			if (header < 'a' || header > 'z') {
//				user.setHeader("#");
//			}
//		}
//	}

//	@Override
//	public void gotResult(int code, String alias, Set<String> tags) {
//		String logs ;
//		switch (code) {
//			case 0:
//				logs = "Set tag and alias success, alias = " + alias + "; tags = " + tags;
//				break;
//			
//			default:
//				logs = "Failed with errorCode = " + code + " alias = " + alias + "; tags = " + tags;
//		}
//		if(!TextUtils.isEmpty(logs)){
//			System.out.println("---gotResult---"+logs);
//		}
//	}
	
}
